package com.cool.reggie.modules.orders.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cool.reggie.core.exception.CustomException;
import com.cool.reggie.modules.addressBook.entity.AddressBookEntity;
import com.cool.reggie.modules.addressBook.service.AddressBookService;
import com.cool.reggie.modules.orderDetail.entity.OrderDetailEntity;
import com.cool.reggie.modules.orderDetail.service.OrderDetailService;
import com.cool.reggie.modules.orders.dto.OrderDto;
import com.cool.reggie.modules.orders.entity.OrdersEntity;
import com.cool.reggie.modules.orders.mapper.OrdersMapper;
import com.cool.reggie.modules.orders.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cool.reggie.modules.shoppingCart.entity.ShoppingCartEntity;
import com.cool.reggie.modules.shoppingCart.service.ShoppingCartService;
import com.cool.reggie.modules.user.entity.UserEntity;
import com.cool.reggie.modules.user.service.UserService;
import com.cool.reggie.utils.BaseContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 1950735817@qq.com
 * @since 2022-07-20
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersEntity> implements OrdersService {
    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitOrder(OrdersEntity ordersEntity) {
        // 获取用户
        Long userId = BaseContext.getCurrentId();
        UserEntity user = userService.getById(userId);

        // 查询购物车数据
        LambdaQueryWrapper<ShoppingCartEntity> shoppingQueryWrapper = new LambdaQueryWrapper<>();
        shoppingQueryWrapper.eq(ShoppingCartEntity::getUserId, BaseContext.getCurrentId());
        List<ShoppingCartEntity> shoppingList = shoppingCartService.list(shoppingQueryWrapper);
        if (shoppingList == null || shoppingList.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 查询地址数据
        Long addressBookId = ordersEntity.getAddressBookId();
        AddressBookEntity addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("地址数据有误，不能下单");
        }

        // 向订单表插入数据
        // 1.生成一个订单号
        long orderId = IdWorker.getId();

        // 2.订单详情列表以及计算总额
        AtomicInteger amount = new AtomicInteger();
        List<OrderDetailEntity> orderDetailEntityList = shoppingList.stream().map((item) -> {
            OrderDetailEntity orderDetail = new OrderDetailEntity();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setNumber(item.getNumber());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 3.设置地址
        String address = (StringUtils.isNotBlank(addressBook.getProvinceName()) ? addressBook.getProvinceName() : "") +
                (StringUtils.isNotBlank(addressBook.getCityName()) ? addressBook.getCityName() : "") +
                (StringUtils.isNotBlank(addressBook.getDistrictName()) ? addressBook.getDistrictName() : "") +
                (StringUtils.isNotBlank(addressBook.getDetail()) ? addressBook.getDetail() : "");

        ordersEntity.setId(orderId);
        ordersEntity.setNumber(String.valueOf(orderId));
        ordersEntity.setStatus(2);
        ordersEntity.setUserId(userId);
        ordersEntity.setOrderTime(new Date());
        ordersEntity.setCheckoutTime(new Date());
        ordersEntity.setAmount(new BigDecimal(amount.get()));
        ordersEntity.setUserName(user.getName());
        ordersEntity.setConsignee(addressBook.getConsignee());
        ordersEntity.setPhone(addressBook.getPhone());
        ordersEntity.setAddress(address);

        this.save(ordersEntity);

        // 向订单详情表插入数据
        orderDetailService.saveBatch(orderDetailEntityList);

        // 购物车清空
        shoppingCartService.remove(shoppingQueryWrapper);
    }

    @Override
    public Page<OrderDto> queryList(Page<OrdersEntity> objectPage) {

        Page<OrdersEntity> page = this.page(objectPage);

        List<OrdersEntity> records = page.getRecords();

        List<OrderDto> list = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);

            LambdaQueryWrapper<OrderDetailEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetailEntity::getOrderId, item.getId());
            List<OrderDetailEntity> orderDetail = orderDetailService.list(queryWrapper);
            orderDto.setOrderDetails(orderDetail);
            return orderDto;
        }).collect(Collectors.toList());



        Page<OrderDto> orderDtoPage = new Page<OrderDto>(objectPage.getCurrent(),objectPage.getSize());
        orderDtoPage.setRecords(list);
        return orderDtoPage;
    }
}
